package com.fsd.admin.service.impl;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import com.fsd.core.util.DateTimeUtil;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.VerticalAlignment;
import jxl.write.*;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.fsd.core.common.BusinessException;
import com.fsd.core.service.impl.BaseServiceImpl;
import com.fsd.core.util.Config;
import com.fsd.core.util.ParametersUtil;
import com.fsd.admin.model.A_Employee;
import com.fsd.admin.model.Sys_SystemLog;
import com.fsd.admin.service.Sys_SystemLogService;
import com.fsd.admin.dao.Sys_SystemLogDao;
import com.google.gson.Gson;

@Repository("Sys_SystemLogServiceImpl")
public class Sys_SystemLogServiceImpl extends BaseServiceImpl<Sys_SystemLog, String> implements Sys_SystemLogService{
	
	private static final Logger log = Logger.getLogger(Sys_SystemLogServiceImpl.class);
    private String depict = "系统日志";
    
    @Resource(name = "Sys_SystemLogDaoImpl")
	public void setBaseDao(Sys_SystemLogDao Sys_SystemLogDao) {
		super.setBaseDao(Sys_SystemLogDao);
	}
	
	@Resource(name = "Sys_SystemLogDaoImpl")
	private Sys_SystemLogDao objectDao;
	
	
	/**
	 * 加载分页数据
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public ParametersUtil getObjectPageList(ParametersUtil param, A_Employee employee) throws Exception{
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("companyid", employee.getCompanyid()));
		c.addOrder(Order.desc("logtime"));
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("stime") != null && !"".equals(objectMap.get("stime"))){
				c.add(Restrictions.ge("logtime", objectMap.get("stime")));
			}
			if(objectMap.get("etime") != null && !"".equals(objectMap.get("etime"))){
				c.add(Restrictions.le("logtime", objectMap.get("etime")));
			}
			if(objectMap.get("employeename") != null && !"".equals(objectMap.get("employeename"))){
				c.add(Restrictions.like("employeename", "%" + objectMap.get("employeename") + "%"));
			}
			if(objectMap.get("logtype") != null && !"".equals(objectMap.get("logtype"))){
				c.add(Restrictions.eq("logtype", objectMap.get("logtype")));
			}
		}
		return objectDao.findPager(param , c);
	}
	
	/**
	 * 加载分页数据，普通操作 
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public ParametersUtil getObjectPageListCZ(ParametersUtil param, A_Employee employee) throws Exception{
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("companyid", employee.getCompanyid()));
		String[] types = new String[]{
				Config.LOGTYPEDL,
				Config.LOGTYPEMM,
				Config.LOGTYPEBC,
				Config.LOGTYPESC,
				Config.LOGTYPEQT
		};
		c.add(Restrictions.in("logtype", types));
		c.addOrder(Order.desc("logtime"));
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("stime") != null && !"".equals(objectMap.get("stime"))){
				c.add(Restrictions.ge("logtime", objectMap.get("stime")));
			}
			if(objectMap.get("etime") != null && !"".equals(objectMap.get("etime"))){
				c.add(Restrictions.le("logtime", objectMap.get("etime")));
			}
			if(objectMap.get("employeename") != null && !"".equals(objectMap.get("employeename"))){
				c.add(Restrictions.like("employeename", "%" + objectMap.get("employeename") + "%"));
			}
			if(objectMap.get("logtype") != null && !"".equals(objectMap.get("logtype"))){
				c.add(Restrictions.eq("logtype", objectMap.get("logtype")));
			}
		}
		return objectDao.findPager(param , c);
	}
	
	/**
	 * 加载分页数据，安全操作
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public ParametersUtil getObjectPageListAQ(ParametersUtil param, A_Employee employee) throws Exception{
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("companyid", employee.getCompanyid()));
		String[] types = new String[]{
				Config.LOGTYPEDL,
				Config.LOGTYPEDLSB,
				Config.LOGTYPEMM,
				Config.LOGTYPEAQ,
				Config.LOGTYPEMGBC,
				Config.LOGTYPEMGCX,
				Config.LOGTYPEMGSZ
		};
		c.add(Restrictions.in("logtype", types));
		c.addOrder(Order.desc("logtime"));
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("stime") != null && !"".equals(objectMap.get("stime"))){
				c.add(Restrictions.ge("logtime", objectMap.get("stime")));
			}
			if(objectMap.get("etime") != null && !"".equals(objectMap.get("etime"))){
				c.add(Restrictions.le("logtime", objectMap.get("etime")));
			}
			if(objectMap.get("employeename") != null && !"".equals(objectMap.get("employeename"))){
				c.add(Restrictions.like("employeename", "%" + objectMap.get("employeename") + "%"));
			}
			if(objectMap.get("logtype") != null && !"".equals(objectMap.get("logtype"))){
				c.add(Restrictions.eq("logtype", objectMap.get("logtype")));
			}
		}
		return objectDao.findPager(param , c);
	}
	
	/**
	 * 保存角色
	 * @throws Exception
	 */
	public void saveObject(String logType, String logDepict, A_Employee employee, Class clazz) throws Exception{
		Sys_SystemLog obj = new Sys_SystemLog();
		obj.setId(this.getUUID());//设置主键
		obj.setCompanyid(employee.getCompanyid());//所属单位
		obj.setLogtime(this.getData());//设置添加日期
		obj.setEmployeeid(employee.getId());//设置添加用户id
		obj.setEmployeename(employee.getRealname());//设置添加用户姓名
		if (logType.equals(Config.LOGTYPEDL)){
			obj.setLogtype(Config.LOGTYPEDL);
			obj.setLogtypename(Config.LOGTYPEDLNAME);
			obj.setLogdepict("登录操作：" + logDepict);
		}else if (logType.equals(Config.LOGTYPEDLSB)){
			obj.setLogtype(Config.LOGTYPEDLSB);
			obj.setLogtypename(Config.LOGTYPEDLSBNAME);
			obj.setLogdepict("登录失败：" + logDepict);
		}else if (logType.equals(Config.LOGTYPEMM)){
			obj.setLogtype(Config.LOGTYPEMM);
			obj.setLogtypename(Config.LOGTYPEMMNAME);
			obj.setLogdepict("密码操作：" + logDepict);
		}else if (logType.equals(Config.LOGTYPEBC)){
			obj.setLogtype(Config.LOGTYPEBC);
			obj.setLogtypename(Config.LOGTYPEBCNAME);
			obj.setLogdepict("保存操作：" + logDepict);
		}else if (logType.equals(Config.LOGTYPESC)){
			obj.setLogtype(Config.LOGTYPESC);
			obj.setLogtypename(Config.LOGTYPESCNAME);
			obj.setLogdepict("删除操作：" + logDepict);
		}else if (logType.equals(Config.LOGTYPEAQ)){
			obj.setLogtype(Config.LOGTYPEAQ);
			obj.setLogtypename(Config.LOGTYPEAQNAME);
			obj.setLogdepict("安全操作：" + logDepict);
		}else if (logType.equals(Config.LOGTYPEMGSZ)){
			obj.setLogtype(Config.LOGTYPEMGSZ);
			obj.setLogtypename(Config.LOGTYPEMGSZNAME);
			obj.setLogdepict("敏感标志设置：" + logDepict);
		}else if (logType.equals(Config.LOGTYPEMGBC)){
			obj.setLogtype(Config.LOGTYPEMGBC);
			obj.setLogtypename(Config.LOGTYPEMGBCNAME);
			obj.setLogdepict("敏感信息保存：" + logDepict);
		}else if (logType.equals(Config.LOGTYPEMGCX)){
			obj.setLogtype(Config.LOGTYPEMGCX);
			obj.setLogtypename(Config.LOGTYPEMGCXNAME);
			obj.setLogdepict("敏感信息查询：" + logDepict);
		}else{
			obj.setLogtype(Config.LOGTYPEQT);
			obj.setLogtypename(Config.LOGTYPEQTNAME);
			obj.setLogdepict("其他操作：" + logDepict);
		}
		obj.setRemark(clazz.getName());
		objectDao.save(obj);
		log.info(obj.getLogtime() + "--" + obj.getEmployeename() + "--" + obj.getLogdepict() + "--" + clazz.getName());
	}
	
	/**
	 * 根据ID加载对象
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
	public Sys_SystemLog getObjectById(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("id") == null && "".equals(objectMap.get("id"))){
			throw new BusinessException(depict + "获取缺少ID参数!");
		}
		Sys_SystemLog obj = objectDao.get(objectMap.get("id").toString());
		if(obj == null){
			throw new BusinessException(depict + "数据不存在!");
		}
		return obj;
	}

	/**
	 * 加载导出数据
	 * @return
	 * @throws Exception
	 */
	private List<Sys_SystemLog> getObjectList(ParametersUtil param, A_Employee employee) throws Exception{
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("companyid", employee.getCompanyid()));
		c.addOrder(Order.desc("logtime"));
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("stime") != null && !"".equals(objectMap.get("stime"))){
				c.add(Restrictions.ge("logtime", objectMap.get("stime")));
			}
			if(objectMap.get("etime") != null && !"".equals(objectMap.get("etime"))){
				c.add(Restrictions.le("logtime", objectMap.get("etime")));
			}
			if(objectMap.get("employeename") != null && !"".equals(objectMap.get("employeename"))){
				c.add(Restrictions.like("employeename", "%" + objectMap.get("employeename") + "%"));
			}
			if(objectMap.get("logtype") != null && !"".equals(objectMap.get("logtype"))){
				c.add(Restrictions.eq("logtype", objectMap.get("logtype")));
			}
		}
		return objectDao.getList(c);
	}

	/**
	 * 生成Excel文件
	 * @param url
	 * @throws Exception
	 */
	private void createExcel(List<Sys_SystemLog> sysLogList, String url) throws Exception{
		WritableWorkbook book = Workbook.createWorkbook(new File(url)); //创建可写入的 Excel 工作薄
		WritableCellFormat format = new WritableCellFormat();
		WritableFont font = new WritableFont(WritableFont.ARIAL,16,WritableFont.BOLD); //字形
		format.setFont(font);
		format.setAlignment(Alignment.CENTRE);
		format.setVerticalAlignment(VerticalAlignment.CENTRE);
		format.setBorder(jxl.format.Border.ALL,jxl.format.BorderLineStyle.THIN); //边框

		WritableCellFormat cellformat = new WritableCellFormat();
		cellformat.setBorder(jxl.format.Border.ALL,jxl.format.BorderLineStyle.THIN);
		cellformat.setWrap(true); //设置单元格自适应列宽

		WritableCellFormat headerformat = new WritableCellFormat();
		WritableFont hFont = new WritableFont(WritableFont.ARIAL,WritableFont.DEFAULT_POINT_SIZE,WritableFont.BOLD); //字形加粗
		headerformat.setBorder(jxl.format.Border.ALL,jxl.format.BorderLineStyle.THIN);
		headerformat.setFont(hFont);
		headerformat.setAlignment(Alignment.CENTRE);

		WritableSheet sheet = book.createSheet("安全审计", 0);

		sheet.mergeCells(0,0,4,0); //a:最左上的列，b最左上的行，c最右下的列，d最右下的行 （合并单元格）
		sheet.getSettings().setDefaultColumnWidth(20);
		sheet.setColumnView(0,10); //单独设置列宽 （0代表第几列，10代表宽度）
		sheet.setColumnView(1,25);
		sheet.setColumnView(2,15);
		sheet.setColumnView(3,15);
		sheet.setColumnView(4,80);
		Label label = new Label(0, 0, "安全审计", format);
		sheet.addCell(label);
		for (int i = 0; i < 5; i++) {
			Label label_tem = null;
			switch (i) {
				case 0:
					label_tem = new Label(i, 1, "",headerformat);
					break;
				case 1:
					label_tem = new Label(i, 1, "触发时间",headerformat);
					break;
				case 2:
					label_tem = new Label(i, 1, "操作人姓名",headerformat);
					break;
				case 3:
					label_tem = new Label(i, 1, "日志类型",headerformat);
					break;
				case 4:
					label_tem = new Label(i, 1, "日志描述",headerformat);
					break;
				default:
					break;
			}
			sheet.addCell(label_tem);
		}
		for (int j = 0; j < sysLogList.size(); j++){
			sheet.addCell(new Label(0,j+2, j+1+"",cellformat));
			sheet.addCell(new Label(1,j+2, DateTimeUtil.getNewDateTimeStyle(sysLogList.get(j).getLogtime(), "yyyyMMddHHmmss", "yyyy年MM月dd日 HH时mm分"),cellformat));
			sheet.addCell(new Label(2,j+2, sysLogList.get(j).getEmployeename(),cellformat));
			sheet.addCell(new Label(3,j+2, sysLogList.get(j).getLogtypename(),cellformat));
			sheet.addCell(new Label(4,j+2, sysLogList.get(j).getLogdepict(),cellformat));
		}
		book.write();
		book.close();
	}

	/**
	 * Excel导出
	 */
	public Map<String, String> download(ParametersUtil param, A_Employee employee, String rootPath, String httpRootPath) throws Exception {
		List<Sys_SystemLog> sysLog = this.getObjectList(param, employee);
		String path = "uploadfiles/temp/"+ UUID.randomUUID().toString().trim().replaceAll("-", "")+".xls";
		String url = rootPath+path;
		String httpUrl = httpRootPath+path;
		this.createExcel(sysLog, url);
		Map<String, String> map = new HashMap<String, String>();
		map.put("httpUrl", httpUrl);
		return map;
	}
	
}
